package com.qcby.test;

import java.util.LinkedList;
import java.util.Queue;

public class Stack {
    private Queue<Integer> queue1; // 主队列
    private Queue<Integer> queue2; // 辅助队列

    public Stack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    // 入栈操作
    public void push(int x) {
        queue1.add(x);
    }

    // 出栈操作
    public int pop() {
        while (queue1.size() > 1) {
            queue2.add(queue1.poll());
        }
        int top = queue1.poll();
        // 交换queue1和queue2
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
        return top;
    }

    // 获取栈顶元素
    public int top() {
        while (queue1.size() > 1) {
            queue2.add(queue1.poll());
        }
        int top = queue1.poll();
        queue2.add(top);
        // 交换queue1和queue2
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
        return top;
    }

    // 判断栈是否为空
    public boolean empty() {
        return queue1.isEmpty();
    }

    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push(1);
        stack.push(2);
        System.out.println(stack.top());   // 返回 2
        System.out.println(stack.pop());   // 返回 2
        System.out.println(stack.empty()); // 返回 false
    }
}